package com.parenting.oauth2.service;




import com.parenting.feign.controller.IFeignSystemPlatformUserController;
import com.parenting.model.PlatformUserDTO;
import com.parenting.oauth2.exception.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component("customUserDetailsService") // 不一定不要少了
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private IFeignSystemPlatformUserController feignSystemPlatformUserController;



     @Override
     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 判断用户名是否为空
        if(StringUtils.isEmpty(username)) {
            log.info("================用户名不能为空=================");
            throw new ValidateCodeException("用户名不能为空");
        }
         PlatformUserDTO sysUser = feignSystemPlatformUserController.getParentUserByAccount(username);
        // 2. 通过用户名查询数据库中的用户信息
        if(sysUser == null) {
            log.info("================用户名或密码错误=================");
            throw new ValidateCodeException("用户名或密码错误");
        }
        List<GrantedAuthority> authorities= new ArrayList<>();;
         authorities.add(new SimpleGrantedAuthority("admin"));
            // 5. 构建UserDetails接口的实现类JwtUser对象
            JwtUser jwtUser = new JwtUser( sysUser.getPlatformUserId(),sysUser.getPlatformUserAccount(),sysUser.getPlatformUserAccount(), sysUser.getPlatformUserPassword(),
                    sysUser.getPlatformUserNickname(), sysUser.getPlatformUserHead(), sysUser.getMobile(),sysUser.getIsAccountNonExpired(),
                    sysUser.getIsAccountNonLocked(),sysUser.getIsCredentialsNonExpired(),sysUser.getIsEnabled(),authorities);
            return jwtUser;
    }
}
